package com.tg.push;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.tange.base.toolkit.ProcessUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class AliYunPushFixer {

    private static final String TAG = "AliYunPushFixer";

    private static final int CRASH_LIMIT = 100;
    private static final int CRASH_COUNT = 0;

    private static final String CRASH_DEFINE_FILE_NAME = "com_alibaba_aliyun_crash_defend_sdk_info";

    public static void modifyAliYunInfo(Context context) {

        // 修改两个文件的内容，避免因为SDK内部的闪退保护而未开启推送：

        try {

            if (context == null) return;

            boolean isMainProcess = ProcessUtils.isMainProcess(context);
            if (!isMainProcess) {
                return;
            }

            File filesDir = context.getFilesDir();
            if (filesDir == null) return;

            File file1 = new File(filesDir, CRASH_DEFINE_FILE_NAME);
            File file2 = new File(filesDir, CRASH_DEFINE_FILE_NAME + "_" + context.getPackageName() + ":channel");

            modifyCrashInfo(file1);
            modifyCrashInfo(file2);

        } catch (Throwable ex) {

        }
    }

    private static void modifyCrashInfo(File file) {
        try {
            if (!file.exists()) {
                return;
            }

            Log.i(TAG, "modifyCrashInfo: file = " + file);

            InputStreamReader isr = new InputStreamReader(new FileInputStream(file),"UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            StringBuilder builder = new StringBuilder();
            while((line = br.readLine()) != null){
                builder.append(line);
            }
            br.close();
            isr.close();

            String content = builder.toString();

            Log.i(TAG, "modifyCrashInfo:     content = " + content);

            if (TextUtils.isEmpty(content)) {
                Log.i(TAG, "modifyCrashInfo:     content is EMPTY");
                return;
            }

            JSONObject jsonObject = new JSONObject(content);

            Log.i(TAG, "modifyCrashInfo:     jsonObject = " + jsonObject);

            if (jsonObject == null) {
                return;
            }

            JSONArray jsonArray = jsonObject.has("sdkList") ? jsonObject.getJSONArray("sdkList") : null;
            if (jsonArray == null) {
                return;
            }

            boolean hasChanged = false;

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject object = jsonArray.getJSONObject(i);
                if (object != null) {
                    Log.i(TAG, "modifyCrashInfo:     found element:");
                    if (object.has("crashLimit")) {
                        int originCrashLimit = object.getInt("crashLimit");
                        Log.i(TAG, "modifyCrashInfo:         originCrashLimit = " + originCrashLimit);
                        if (originCrashLimit != CRASH_LIMIT) {
                            object.put("crashLimit", CRASH_LIMIT);
                            hasChanged = true;
                            Log.i(TAG, "modifyCrashInfo:         crashLimit rewrite as " + CRASH_LIMIT);
                        }
                    }
                    if (object.has("crashCount")) {
                        int originCrashCount = object.getInt("crashCount");
                        Log.i(TAG, "modifyCrashInfo:         originCrashCount = " + originCrashCount);
                        if (originCrashCount != CRASH_COUNT) {
                            object.put("crashCount", CRASH_COUNT);
                            hasChanged = true;
                            Log.i(TAG, "modifyCrashInfo:         crashCount rewrite as " + CRASH_COUNT);
                        }
                    }
                }
            }

            if (hasChanged) {
                OutputStream os = new FileOutputStream(file);
                os.write(jsonObject.toString().getBytes("utf-8"));
                Log.i(TAG, "modifyCrashInfo:     write new content = " + jsonObject);
            } else {
                Log.i(TAG, "modifyCrashInfo:     file content not changed");
            }

        } catch (Throwable ex) {
            Log.i(TAG, "modifyCrashInfo:     error = " + ex);
        }

    }
}
